package teacher_que

import (
	"Student_Mental/DBconfing"
	"Student_Mental/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func returnErr(err error, c *gin.Context) {

	if err != nil {
		c.JSON(200, gin.H{
			"code": 1,
			"msg":  err.Error(),
		})
	}
}

// ListPaper 试卷列表
func ListPaper(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	rows, err := sqlDb.Query("SELECT * FROM Paper")
	returnErr(err, c)
	//遍历打印
	var queList []model.Paper
	for rows.Next() {
		var s model.Paper
		err = rows.Scan(&s.Id, &s.Title, &s.Status, &s.ScoreLine, &s.Score, &s.Context, &s.CreatedBy, &s.CreateTime)
		data := model.Paper{
			Id:         s.Id,
			Title:      s.Title,
			Status:     s.Status,
			ScoreLine:  s.ScoreLine,
			Score:      s.Score,
			Context:    s.Context,
			CreatedBy:  s.CreatedBy,
			StringTime: s.CreateTime.Format("2006-01-02 15:04:05"),
		}
		queList = append(queList, data)
	}

	c.HTML(http.StatusOK, "Paper_list.html", gin.H{
		"code": 0,
		"data": queList,
	})
	//用完关闭
	rows.Close()
	sqlDb.Close()
}

// AddPaper 提交试卷添加
func AddPaper(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	title := c.PostForm("title")
	context := c.PostForm("context")
	createdBy, _ := c.Cookie("Name")
	if title != "" {
		rs, err := sqlDb.Exec("insert into Paper(title,context,createdBy,create_time)values (?,?,?,?)", title, context, createdBy, time.Now())
		returnErr(err, c)
		rowCount, err := rs.RowsAffected()
		returnErr(err, c)
		if rowCount > 0 {
			c.JSON(200, gin.H{
				"code": 0,
			})
		} else {
			returnErr(err, c)
		}
	}
	sqlDb.Close()
}

//DelPaper 删除一张试卷
func DelPaper(c *gin.Context) {
	id := c.Param("id")
	sqlDb, _ := DBconfing.Mysql()
	sqlStr := "delete Paper,question from Paper left join question on Paper.id = question.Paper_id where Paper.id = ?"
	res, err := sqlDb.Exec(sqlStr, id)
	returnErr(err, c)
	reslist, _ := res.RowsAffected()
	if reslist > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 1,
		})
	}
	sqlDb.Close()
}

// EditPaper 编辑试卷
func EditPaper(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	title := c.PostForm("title")
	context := c.PostForm("context")
	id := c.PostForm("question-id")
	if title != "" {
		rs, err := sqlDb.Exec("update Paper set title=?,context=? where id=?", title, context, id)
		returnErr(err, c)
		rowCount, err := rs.RowsAffected()
		returnErr(err, c)
		if rowCount >= 0 {
			c.JSON(200, gin.H{
				"code": 0,
			})
			return
		} else {
			returnErr(err, c)
		}
	}
	sqlDb.Close()
}

// EditPaper_html 编辑试卷
func EditPaper_html(c *gin.Context) {
	id := c.Param("id")
	sqlDb, _ := DBconfing.Mysql()
	var status string
	sqlDb.QueryRow("SELECT status FROM Paper where id=?", id).Scan(&status)
	if status == "-1" {
		c.HTML(200, "editPaper.html", gin.H{
			"paperId": id,
		})
	} else {
		c.String(200, "试卷已经发布无法修改")
	}
	sqlDb.Close()

}

// GetPaper 获取一张试卷
func GetPaper(c *gin.Context) {
	id := c.Param("id")
	sqlDb, _ := DBconfing.Mysql()
	var questionTitle model.Paper
	err := sqlDb.QueryRow("SELECT * FROM Paper where id=?", id).Scan(&questionTitle.Id, &questionTitle.Title, &questionTitle.Status, &questionTitle.ScoreLine, &questionTitle.Score, &questionTitle.Context, &questionTitle.CreatedBy, &questionTitle.CreateTime)
	returnErr(err, c)
	rows, err1 := sqlDb.Query("SELECT * FROM question where Paper_id=?", id)
	returnErr(err1, c)
	var questions []model.Question
	for rows.Next() {
		var q model.Question
		err = rows.Scan(&q.Id, &q.PaperId, &q.Number, &q.Question, &q.Options, &q.Score, &q.CreateTime, &q.Factor)
		data := model.Question{
			Id:         q.Id,
			PaperId:    q.PaperId,
			Number:     q.Number,
			Question:   q.Question,
			Options:    q.Options,
			Score:      q.Score,
			StringTime: q.CreateTime.Format("2006-01-02 15:04:05"),
			Factor:     q.Factor,
		}
		questions = append(questions, data)
	}

	c.JSON(200, gin.H{
		"code":            0,
		"PaperId":         questionTitle.Id,
		"PaperTitle":      questionTitle.Title,
		"PaperScore_line": questionTitle.ScoreLine,
		"PaperScore":      questionTitle.Score,
		"paperContext":    questionTitle.Context,
		"questions":       questions,
	})
	rows.Close()
	sqlDb.Close()
}

type question struct {
	Questionname   string
	QuestionOption []string
	OptionScore    []string
}

// EditQusetion 添加问题
func EditQusetion(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	//接收json数据
	var que []question
	var sqlList []string
	c.ShouldBindBodyWith(&que, binding.JSON)
	fmt.Println(que)
	for k, v := range que {
		sql := fmt.Sprintf("(%d,%d,'%s','%s','%s','%s'),",
			id,
			k+1,
			v.Questionname,
			v.QuestionOption,
			v.OptionScore,
			time.Now().Format("2006-01-02 15:04:05"),
		)
		sqlList = append(sqlList, sql)
	}
	if que != nil {
		sqlDB, _ := DBconfing.Mysql()
		//删除之前的
		sqlDB.Exec("delete from question where Paper_id = ?", id)
		//分批插入数据库
		var sqlarr strings.Builder
		sqlTop := "insert into question(Paper_id,number,question,options,score ,create_time)values"
		for k, v := range sqlList {
			if k != 0 && k%50 == 0 {
				sql := sqlTop + sqlarr.String()
				sql = sql[:len(sql)-1]
				sqlDB.Exec(sql)
				sqlarr.Reset()
			}
			sqlarr.WriteString(v)
		}
		sql := sqlTop + sqlarr.String()
		sql = sql[:len(sql)-1]
		sqlDB.Exec(sql)
		sqlDB.Close()
	}
	c.JSON(200, gin.H{
		"code": "0",
	})
}

// SetPaperScore 设置试卷总分和分数线
func SetPaperScore(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	id := c.Param("id")
	scoresum := c.PostForm("score")
	scoreline := c.PostForm("scoreLine")
	if scoresum != "" {
		rs, err := sqlDb.Exec("update Paper set Score_line=?,Score=? where id=?", scoreline, scoresum, id)
		returnErr(err, c)
		rowCount, err := rs.RowsAffected()
		returnErr(err, c)
		if rowCount > 0 {
			c.JSON(200, gin.H{
				"code": 0,
			})
		} else {
			returnErr(err, c)
		}
	}
	sqlDb.Close()
}

// SendPaper 发布试卷
func SendPaper(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	id := c.Param("id")
	status := c.Param("status")
	println(id)
	if status == "-1" {
		rs, err := sqlDb.Exec("update Paper set status=? where id=?", 1, id)
		returnErr(err, c)
		rowCount, err := rs.RowsAffected()
		returnErr(err, c)
		if rowCount > 0 {
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "发布成功",
				"icon": 1,
			})
		} else {
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "试卷已经发布",
				"icon": 0,
			})
		}
	} else if status == "1" {
		rs, err := sqlDb.Exec("update Paper set status=? where id=?", -1, id)
		returnErr(err, c)
		rowCount, err := rs.RowsAffected()
		returnErr(err, c)
		if rowCount > 0 {
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "下架成功",
				"icon": 1,
			})
		} else {
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "试卷已经下架",
				"icon": 0,
			})
		}
	}
	sqlDb.Close()
}

// Finish 完成试卷
func Finish(c *gin.Context) {
	sqlDb, _ := DBconfing.Mysql()
	rows, err := sqlDb.Query("SELECT id, title,context, IFNULL( uc.no_a, 0 ) AS num, createdBy, `status` FROM Paper AS ua LEFT JOIN ( SELECT Paper_id, count( 1 ) AS no_a FROM testrecord GROUP BY Paper_id ) AS uc ON ua.id = uc.Paper_id WHERE ua.`status` = 1")
	returnErr(err, c)
	type finish struct {
		Id           int
		Title        string
		Context      string
		FinishPerson int
		CreatedBy    string
		Status       string
	}
	//遍历打印
	var queList []finish
	for rows.Next() {
		var s finish
		err = rows.Scan(&s.Id, &s.Title, &s.Context, &s.FinishPerson, &s.CreatedBy, &s.Status)
		data := finish{
			Id:           s.Id,
			Title:        s.Title,
			Context:      s.Context,
			FinishPerson: s.FinishPerson,
			CreatedBy:    s.CreatedBy,
			Status:       s.Status,
		}
		queList = append(queList, data)
	}

	c.HTML(http.StatusOK, "finishPaper.html", gin.H{
		"code": 0,
		"data": queList,
	})
	//用完关闭
	rows.Close()
	sqlDb.Close()
}

func FinishInfo(c *gin.Context) {
	id := c.Param("id")
	sqlDb, _ := DBconfing.Mysql()
	var s model.Paper
	sqlDb.QueryRow("SELECT * FROM Paper where id=?", id).Scan(&s.Id, &s.Title, &s.Status, &s.ScoreLine, &s.Score, &s.Context, &s.CreatedBy, &s.CreateTime)
	rows, err := sqlDb.Query("SELECT testrecord.id,stu_id,score,student_name,avatar,IF(score>(SELECT Score_line FROM Paper WHERE id=?),\"通过\",\"不通过\")AS pass FROM testrecord left join student ON testrecord.stu_id=student.id WHERE paper_id =?", id, id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1,
			"err":  err,
		})
	}
	type studentRes struct {
		Id     int
		Uid    int
		Score  int
		Name   string
		Avatar string
		Status string
	}
	var queList1 []studentRes
	var queList2 []studentRes
	for rows.Next() {
		var s studentRes
		rows.Scan(&s.Id, &s.Uid, &s.Score, &s.Name, &s.Avatar, &s.Status)
		data := studentRes{
			Id:     s.Id,
			Uid:    s.Uid,
			Score:  s.Score,
			Name:   s.Name,
			Avatar: s.Avatar,
			Status: s.Status,
		}
		if data.Status == "通过" {
			queList1 = append(queList1, data)
		} else {
			queList2 = append(queList2, data)
		}
	}
	c.HTML(http.StatusOK, "finishPaperInfo.html", gin.H{
		"code": 0,
		"data": s,
		"res":  queList1,
		"res2": queList2,
	})
	rows.Close()
	sqlDb.Close()
}
